package com.example.forum.interceptor;
import com.example.forum.config.AppConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * date: 2024/09/10 15:44<br/>
 * Description:
 * 拦截http请求，判断是否为登录状态
 *
 * @throws Exception
 * @author: jmy <br/>
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${spring-forum.login.url}")
    private String defaultURL;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //判断session是否有效
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            //用户已登录，校验通过
            return true;
        }
        //校验url是否正确
        if (!defaultURL.startsWith("/")) {
            defaultURL = "/" + defaultURL;
        }
        //登录状态校验不通过 跳转到登录界面
        response.sendRedirect(defaultURL);
        return true;
    }
}
